package com.sxt.core.discovery.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import com.sxt.core.discovery.Discovery;

/**
 * 服务发现的实现类，zookeeper实现
 * 
 * @author Liushuangxi
 *
 */
public class ZKDiscoveryImpl implements Discovery {
	// 初始化Map集合，作为缓存
	private static Map<String, List<String>> cache= new HashMap<>();
	private static ZkClient zkClient = null;
	static {
		zkClient = new ZkClient("192.168.15.137:2181,192.168.15.137:2182,192.168.15.137:2183");
	}

	@Override
	public List<String> discovery(String serverName) {
		//判断缓存是否存在serverName对应的地址
		if(cache.containsKey(serverName)) {
			return cache.get(serverName);
		}
		
		// 判断zookeeper里面是否存在serverName
		if(!zkClient.exists("/"+serverName)) {
			return null;
		}
		// 从zookeeper里面获取
		List<String> childrens = zkClient.getChildren("/"+serverName);
		// 监听节点的改变
		zkClient.subscribeChildChanges("/"+serverName, new IZkChildListener() {
			
			@Override
			public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
				System.out.println("有服务"+parentPath+"上线或下线"+",当前服务列表为："+currentChilds);
				cache.put(serverName, currentChilds);
			}
		});
		cache.put(serverName, childrens);
		return childrens;
	}
	
	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		ZKDiscoveryImpl zk = new ZKDiscoveryImpl();
		List<String> discovery = zk.discovery("ADD");
		System.out.println(discovery);
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
